//
//  WBStatus.m
//  WeiBo
//
//  Created by wbs on 17/2/13.
//  Copyright © 2017年 xiaomaolv. All rights reserved.
//

#import "WBStatus.h"

#import "NSDate+YTT.h"
#import "RegexKitLite.h"
#import "WBEmotionTool.h"
#import "BSEmotionModel.h"
#import "WBUser.h"

/// 标识：链接类型（话题／@／http链接）
NSString *const kWBLinkResultType = @"kWBLinkResultType";
/// 标识：链接的具体文本
NSString *const kWBLinkText = @"kWBLinkText";

@implementation WBStatus

+ (NSDictionary *)mj_objectClassInArray
{
    return @{
             @"pic_urls" : @"WBStatusPhoto"
             };
}

+ (NSDictionary *)mj_replacedKeyFromPropertyName
{
    return @{
             @"idNum" : @"id"
             };
}

- (NSString *)created_at
{
    // 1.获得微博的发送时间
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"EEE MMM dd HH:mm:ss Z yyyy";
    // 真机调试下, 必须加上这段
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    NSDate *createdDate = [fmt dateFromString:_created_at];
    
    // 2.判断微博发送时间 和 现在时间 的差距
    if (createdDate.isToday) { // 今天
        if (createdDate.deltaWithNow.hour >= 1) {
            return [NSString stringWithFormat:@"%ld小时前", (long)createdDate.deltaWithNow.hour];
        } else if (createdDate.deltaWithNow.minute >= 1) {
            return [NSString stringWithFormat:@"%ld分钟前", (long)createdDate.deltaWithNow.minute];
        } else {
            return @"刚刚";
        }
    } else if (createdDate.isYesterday) { // 昨天
        fmt.dateFormat = @"昨天 HH:mm";
        return [fmt stringFromDate:createdDate];
    } else if (createdDate.isThisYear) { // 今年(至少是前天)
        fmt.dateFormat = @"MM-dd HH:mm";
        return [fmt stringFromDate:createdDate];
    } else { // 非今年
        fmt.dateFormat = @"yyyy-MM-dd HH:mm";
        return [fmt stringFromDate:createdDate];
    }
}

- (void)setSource:(NSString *)source
{
    NSInteger loc = [source rangeOfString:@">"].location + 1;
    NSInteger length = [source rangeOfString:@"</"].location - loc;
    source = [source substringWithRange:NSMakeRange(loc, length)];
    _source = [NSString stringWithFormat:@"来自%@", source];
}

- (void)setText:(NSString *)text
{
    _text = [text copy];
    [self createAttributedText];
}

- (void)setUser:(WBUser *)user
{
    _user = user;
    [self createAttributedText];
}

- (void)setRetweeted_status:(WBStatus *)retweeted_status
{
    _retweeted_status = retweeted_status;
    
    self.retweeted = NO;
    retweeted_status.retweeted = YES;
}

- (void)setRetweeted:(BOOL)retweeted
{
    _retweeted = retweeted;
    
    [self createAttributedText];
}

- (void)createAttributedText
{
    if (self.text && self.user) {
        if (self.retweeted) {
            NSString *totalText = [NSString stringWithFormat:@"@%@ : %@", self.user.name, self.text];
            NSAttributedString *attributedString = [self attributedStringWithText:totalText];
            self.attributeText = attributedString;
        } else {
            NSAttributedString *attributedString = [self attributedStringWithText:self.text];
            self.attributeText = attributedString;
        }
    }
}

- (NSAttributedString *)attributedStringWithText:(NSString *)text
{
    // regexResults临时的用于排序，用WBRegexResult模型方便排序
    NSMutableArray<WBRegexResult *> *regexResults = [NSMutableArray arrayWithCapacity:0];
    
    // 匹配表情
    NSString *emotionRegex = @"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]";
    [text enumerateStringsMatchedByRegex:emotionRegex usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
        WBRegexResult *result = [[WBRegexResult alloc] init];
        result.string = *capturedStrings;
        result.range = *capturedRanges;
        result.emotion = YES;
        [regexResults addObject:result];
    }];
    
    // 匹配非表情
    [text enumerateStringsSeparatedByRegex:emotionRegex usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
        WBRegexResult *result = [[WBRegexResult alloc] init];
        result.string = *capturedStrings;
        result.range = *capturedRanges;
        result.emotion = NO;
        [regexResults addObject:result];
    }];
    
    // 排序
    [regexResults sortUsingComparator:^NSComparisonResult(WBRegexResult * _Nonnull obj1, WBRegexResult * _Nonnull obj2) {
        NSInteger loc1 = obj1.range.location;
        NSInteger loc2 = obj2.range.location;
        if (loc1 < loc2) {
            return NSOrderedAscending;
        } else if (loc1 > loc2) {
            return NSOrderedDescending;
        } else {
            return NSOrderedSame;
        }
    }];
    
    NSMutableAttributedString *attributeText = [[NSMutableAttributedString alloc] init];
    
    [regexResults enumerateObjectsUsingBlock:^(WBRegexResult * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.isEmotion) { // 是表情
            UIImage *image = [WBEmotionTool baseEmotionSmallPictureWithDes:obj.string].smallImage;
            if (image) {
                NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
                attachment.image = image;
                attachment.bounds = CGRectMake(0, -3, kStatusRetweetedTextFont.lineHeight, kStatusRetweetedTextFont.lineHeight);
                NSAttributedString *attachString = [NSAttributedString attributedStringWithAttachment:attachment];
                [attributeText appendAttributedString:attachString];
            } else { // 找不到，说明新浪图片更新了，匹配不到，这是返回表情的文字描述
                NSMutableAttributedString *substr = [[NSMutableAttributedString alloc] initWithString:obj.string];
                [substr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, substr.length)];
                [attributeText appendAttributedString:substr];
            }
        } else { // 非表情
            NSMutableAttributedString *substr = [[NSMutableAttributedString alloc] initWithString:obj.string];
            // 非表情的常规富文本颜色
            [substr addAttribute:NSForegroundColorAttributeName value:kStatusRetweetedTextColor range:NSMakeRange(0, substr.length)];
            // 匹配话题（#...#）
            NSString *trendRegex = @"#[a-zA-Z0-9\\u4e00-\\u9fa5\\s+]+#";
            [obj.string enumerateStringsMatchedByRegex:trendRegex usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
                [substr addAttribute:NSForegroundColorAttributeName value:kStatusRegexTopicColor range:*capturedRanges];
                [substr addAttribute:kWBLinkText value:*capturedStrings range:*capturedRanges];
                [substr addAttribute:kWBLinkResultType value:[NSNumber numberWithInteger:WBLinkResultType_Trend] range:*capturedRanges];
            }];
            // 匹配提到（@...）
            NSString *mentionRegex = @"@[a-zA-Z0-9_\\u4e00-\\u9fa5\\-]+ ?";
            [obj.string enumerateStringsMatchedByRegex:mentionRegex usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
                [substr addAttribute:NSForegroundColorAttributeName value:kStatusRegexAtColor range:*capturedRanges];
                [substr addAttribute:kWBLinkText value:*capturedStrings range:*capturedRanges];
                [substr addAttribute:kWBLinkResultType value:[NSNumber numberWithInteger:WBLinkResultType_At] range:*capturedRanges];
            }];
            // 匹配超链接
            NSString *httpRegex = @"http(s)?://([a-zA-Z|\\d]+\\.)+[a-zA-Z|\\d]+(/[a-zA-Z|\\d|\\-|\\+|_./?%&=]*)?";
            [obj.string enumerateStringsMatchedByRegex:httpRegex usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
                [substr addAttribute:NSForegroundColorAttributeName value:kStatusRegexHyperlinkColor range:*capturedRanges];
                [substr addAttribute:kWBLinkText value:*capturedStrings range:*capturedRanges];
                [substr addAttribute:kWBLinkResultType value:[NSNumber numberWithInteger:WBLinkResultType_Link] range:*capturedRanges];
            }];
            [attributeText appendAttributedString:substr];
        }
    }];
    
    [attributeText addAttribute:NSFontAttributeName value:kStatusRetweetedTextFont range:NSMakeRange(0, attributeText.length)];
    
    // 计算出所有的链接位置
    NSMutableArray<WBLinkResult *> *linkResults = [NSMutableArray arrayWithCapacity:0];
    [attributeText enumerateAttributesInRange:NSMakeRange(0, attributeText.length) options:0 usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
        NSString *linkString = attrs[kWBLinkText];
        if (linkString) {
            WBLinkResultType linkType = [attrs[kWBLinkResultType] integerValue];
            WBLinkResult *linkResult = [WBLinkResult linkResultWithString:linkString range:range linkResultType:linkType];
            [linkResults addObject:linkResult];
        }
    }];
    self.linkResults = linkResults;
    
    return attributeText;
}

@end


@implementation WBRegexResult

@end


@implementation WBLinkResult

+ (WBLinkResult *)linkResultWithString:(NSString *)string range:(NSRange)range linkResultType:(WBLinkResultType)linkResultType
{
    return [[self alloc] initWithString:string range:range linkResultType:linkResultType];
}

- (WBLinkResult *)initWithString:(NSString *)string range:(NSRange)range linkResultType:(WBLinkResultType)linkResultType
{
    self = [super init];
    if (self) {
        _string = string;
        _range = range;
        _linkResultType = linkResultType;
    }
    return self;
}

@end


@implementation WBVisialLink

@end

